package com.yanqu.road.server.manager.monopolymarket;

import com.yanqu.road.entity.enums.eMonopolyMarketResType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.monopolymarket.*;
import com.yanqu.road.entity.monopolymarket.config.MonopolyMarketBackEndConfig;
import com.yanqu.road.entity.monopolymarket.config.MonopolyMarketCrossConfig;
import com.yanqu.road.entity.monopolymarket.config.MonopolyMarketResConfigData;
import com.yanqu.road.entity.monopolymarket.fortress.MonopolyMarketFortressRewardData;
import com.yanqu.road.entity.monopolymarket.group.MonopolyMarketCrossGroup;
import com.yanqu.road.entity.monopolymarket.office.*;
import com.yanqu.road.entity.monopolymarket.resgrab.*;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.logic.bussiness.monopolymarket.MonopolyMarketBussiness;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.pb.monopolymarket.MonopolyMarketProto;
import com.yanqu.road.pb.worldmessage.WorldMessageProto;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.group.SystemGroupChatMgr;
import com.yanqu.road.server.manager.user.CrossUserMgr;
import com.yanqu.road.server.manger.MonopolyMarketCommonMgr;
import com.yanqu.road.server.manger.plugin.ManagerReloadListener;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.utils.BitUtil;
import com.yanqu.road.utils.ConfigHelper;
import com.yanqu.road.utils.date.DateHelper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @Description 榷场
 * @Author cwq
 * @Data 2021/8/11 18:02
 */
public class MonopolyMarketMgr extends TempMgr {

    public static Logger logger = LogManager.getLogger(MonopolyMarketMgr.class.getName());

    /**
     * 分组榷场数据 k:groupId/serverId
     */
    public static Map<Long, MonopolyMarket> groupMonopolyMarketMap = new ConcurrentHashMap();

    /**
     * 配置 k：资源类型
     */
    public static List<MonopolyMarketResConfigData> resConfigList = new ArrayList<>();

    /**
     * 生成格子的 拓展参数配置
     */
    public static MonopolyMarketCrossConfig crossConfig;

    /**
     * 最大公告条数 （默认50 没走配置）
     */
    public final static int NOTICE_MAX_NUM = 50;


    @Override
    public boolean init() throws Exception {
        MonopolyMarketOfficeMgr.maxResGrabFinishId = new AtomicLong(MonopolyMarketBussiness.getMaxOfficeFinishId());
        MonopolyMarketResGrabMgr.maxResGrabFinishId = new AtomicLong(MonopolyMarketBussiness.getMaxResGrabFinishId());
        MonopolyMarketOfficeMgr.userOfficeFinishMap = MonopolyMarketBussiness.getMonopolyMarketOfficeFinishDataMap();
        List<MonopolyMarketResGrabFinishData> finishDataList = MonopolyMarketBussiness.getMonopolyMarketResGrabFinishDataList();
        // 资源结算奖励
        for (MonopolyMarketResGrabFinishData item : finishDataList) {
            if (!item.getIsJoinRank()) {
                MonopolyMarketResGrabMgr.userResGrabRankMap.put(item.getId(), item);
            }
            if (!item.getIsReceive()) {
                List<MonopolyMarketResGrabFinishData> list = MonopolyMarketResGrabMgr.userResGrabFinishMap.get(item.getUserId());
                if (list == null) {
                    list = new ArrayList<>();
                    MonopolyMarketResGrabMgr.userResGrabFinishMap.put(item.getUserId(), list);
                }
                list.add(item);
            }
        }
        // 要塞奖励
        List<MonopolyMarketFortressRewardData> fortressRewardList = MonopolyMarketBussiness.getMonopolyMarketFortressRewardDataList();
        for (MonopolyMarketFortressRewardData item : fortressRewardList) {
            List<MonopolyMarketFortressRewardData> list = MonopolyMarketFortressMgr.userRewardMap.get(item.getUserId());
            if(list == null){
                list = new ArrayList<>();
                MonopolyMarketFortressMgr.userRewardMap.put(item.getUserId(), list);
            }
            list.add(item);
        }

        reload();
        return true;
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        for (MonopolyMarketCrossGroup item : MonopolyMarketCrossGroupMgr.crossGroupMap.values()) {
            if (item.getState() != 1) {
                // 分组关闭
                continue;
            }
            MonopolyMarket monopolyMarket = groupMonopolyMarketMap.get(item.getGroupId());
            if (monopolyMarket == null) {
                // 新增
                createMonopolyMarket(item);
            }
        }
        // 检查改变的分组
        Set<Long> groupOrConfigChangeServerIdSet = checkGroupChange(false);
        // 校验配置是否发生改变
        boolean configChange = MonopolyMarketConfigMgr.checkConfigChange(false);
        if (configChange) {
            for (MonopolyMarketCrossGroup item : MonopolyMarketCrossGroupMgr.crossGroupMap.values()) {
                if (item.getState() == 1) {
                    groupOrConfigChangeServerIdSet.addAll(item.getServerList());
                }
            }
        }
        addServerGroupReloadListener();
        return true;
    }

    private void addServerGroupReloadListener() {
        MonopolyMarketCrossGroupMgr.addReloadListener(new ManagerReloadListener() {
            @Override
            public void notifyReload() {
                checkGroupChange(true);
            }
        });
    }

    @Override
    public boolean stop() {
        return true;
    }

    @Override
    public boolean save() {
        for (MonopolyMarket item : groupMonopolyMarketMap.values()) {
            MonopolyMarketOfficeMgr.save(item);
            MonopolyMarketResGrabMgr.save(item);
            MonopolyMarketFortressMgr.save(item);

            // 保存公告
            List<MonopolyMarketNoticeData> tempList = new ArrayList<>();
            synchronized (item.needAddNoticeList) {
                tempList.addAll(item.needAddNoticeList);
                item.needAddNoticeList.clear();
            }
            for (MonopolyMarketNoticeData noticeData : tempList) {
                if (noticeData.isInsertOption()) {
                    MonopolyMarketBussiness.addMonopolyMarketNoticeData(noticeData);
                }
            }
        }
        if (crossConfig != null) {
            if (crossConfig.isUpdateOption()) {
                MonopolyMarketBussiness.updateMonopolyMarketCrossConfig(crossConfig);
            } else if (crossConfig.isInsertOption()) {
                MonopolyMarketBussiness.addMonopolyMarketCrossConfig(crossConfig);
            }
        }

        // 资源结算 奖励
        List<MonopolyMarketResGrabFinishData> resGrabFinishList = null;
        synchronized (MonopolyMarketResGrabMgr.tempResGrabFinishList){
            resGrabFinishList = new ArrayList<>(MonopolyMarketResGrabMgr.tempResGrabFinishList);
            MonopolyMarketResGrabMgr.tempResGrabFinishList.clear();
        }
        for(MonopolyMarketResGrabFinishData item : resGrabFinishList){
            if (item.isUpdateOption()) {
                MonopolyMarketBussiness.updateMonopolyMarketResGrabFinishData(item);
            } else if (item.isInsertOption()) {
                MonopolyMarketBussiness.addMonopolyMarketResGrabFinishData(item);
            }
        }

        // 要塞 奖励
        List<MonopolyMarketFortressRewardData> fortressRewarList = null;
        synchronized (MonopolyMarketFortressMgr.tempRewardFinishList){
            fortressRewarList = new ArrayList<>(MonopolyMarketFortressMgr.tempRewardFinishList);
            MonopolyMarketFortressMgr.tempRewardFinishList.clear();
        }
        for(MonopolyMarketFortressRewardData item : fortressRewarList){
            if (item.isUpdateOption()) {
                MonopolyMarketBussiness.updateMonopolyMarketFortressRewardData(item);
            } else if (item.isInsertOption()) {
                MonopolyMarketBussiness.addMonopolyMarketFortressRewardData(item);
            }
        }
        return true;
    }

    /**
     * 创建榷场
     */
    private static MonopolyMarket createMonopolyMarket(MonopolyMarketCrossGroup item) {
        MonopolyMarket monopolyMarket = new MonopolyMarket(item);
        initMonopolyMarket(monopolyMarket);
        groupMonopolyMarketMap.put(item.getGroupId(), monopolyMarket);
        return monopolyMarket;
    }


    /**
     * 进入榷场  尝试领取奖励
     *
     * @param userId
     */
    public static MonopolyMarketProto.MonopolyMarketEnterRespMsgToGameServerMsg.Builder enter(long userId) {
        MonopolyMarketProto.MonopolyMarketEnterRespMsgToGameServerMsg.Builder builder = MonopolyMarketProto.MonopolyMarketEnterRespMsgToGameServerMsg.newBuilder();
        // 资源战
        List<MonopolyMarketProto.MonopolyMarketSynPointSettlementToGameServerMsg> settlementList = MonopolyMarketResGrabMgr.receiveRewardList(userId);
        builder.addAllPointSettlementList(settlementList);
        // 要塞
        List<MonopolyMarketProto.MonopolyMarketFortressTipEntity> fortressSettlementList = MonopolyMarketFortressMgr.receiveRewardList(userId);
        builder.addAllFortressSettlementList(fortressSettlementList);
        return builder;
    }

    /**
     * 查看榷场公告
     *
     * @param type     1榷署 2 王帐  3 王宫
     * @param serverId
     * @return
     */
    public static MonopolyMarketProto.MonopolyMarketGetNoticeRespMsg.Builder getNotice(int type, int page, long serverId) {
        MonopolyMarketProto.MonopolyMarketGetNoticeRespMsg.Builder builder = MonopolyMarketProto.MonopolyMarketGetNoticeRespMsg.newBuilder();
        MonopolyMarket monopolyMarket = getMonopolyMarket(serverId, true);
        if (monopolyMarket == null) {
            builder.setRet(GameErrorCode.E_SYSTEM_NO_OPEN);
            return builder;
        }
        List<MonopolyMarketNoticeData> noticeTempList = new ArrayList<>();
        synchronized (monopolyMarket) {
            List<MonopolyMarketNoticeData> noticeList = monopolyMarket.noticeMap.get(type);
            if (noticeList != null) {
                noticeTempList.addAll(noticeList);
            }
        }
        for (MonopolyMarketNoticeData item : noticeTempList) {
            builder.addNoticeList(MonopolyMarketMgr.builderMonopolyMarketNoticeEntity(item));
        }
        builder.setRet(0);
        return builder;
    }

    /**
     * 获取队伍信息
     *
     * @param userId
     * @param serverId
     */
    public static MonopolyMarketProto.MonopolyMarketGetTeamRespMsg.Builder getTeamList(long userId, long serverId, int type) {
        MonopolyMarketProto.MonopolyMarketGetTeamRespMsg.Builder builder = MonopolyMarketProto.MonopolyMarketGetTeamRespMsg.newBuilder();
        MonopolyMarket monopolyMarket = MonopolyMarketMgr.getMonopolyMarket(serverId, true);
        if (monopolyMarket == null) {
            builder.setRet(GameErrorCode.E_SYSTEM_NO_OPEN);
            return builder;
        }
        synchronized (monopolyMarket) {
            MonopolyMarketResGrab resGrab = monopolyMarket.monopolyMarketResGrab.get(type);
            if(resGrab != null){
                Set<MonopolyMarketResGrabPointInfo> set = resGrab.getUserPointSet(userId,false);
                if(set != null){
                    for (MonopolyMarketResGrabPointInfo pointInfo : set){
                        if(pointInfo.baseInfo.getUserId() != userId){
                            continue;
                        }
                        builder.addTeamList(MonopolyMarketResGrabMgr.builderMonopolyMarketGetTeamEntity(pointInfo));
                    }
                }
            }
        }
        builder.setRet(0);
        return builder;
    }

    /**
     * 获取区服所在的榷场对象
     *
     * @param serverId
     * @return
     */
    public static MonopolyMarket getMonopolyMarket(long serverId, boolean newIfNull) {
        MonopolyMarket monopolyMarket = null;
        MonopolyMarketCrossGroup group = MonopolyMarketCrossGroupMgr.getOpenGroupByServerId(serverId);
        if (group != null) {
            monopolyMarket = groupMonopolyMarketMap.get(group.getGroupId());
        }
        return monopolyMarket;
    }


    /**
     * 创建榷场
     *
     * @param monopolyMarket
     */
    private static void initMonopolyMarket(MonopolyMarket monopolyMarket) {
        synchronized (monopolyMarket) {
            MonopolyMarketOfficeMgr.initOffice(monopolyMarket);
            MonopolyMarketResGrabMgr.initResGrab(monopolyMarket);
            MonopolyMarketFortressMgr.initFortress(monopolyMarket);
        }
    }

    /**
     * 分组变动 重置榷场数据
     *
     * @param monopolyMarket
     * @param newGroup
     */
    private static void resetMonopolyMarket(MonopolyMarket monopolyMarket, MonopolyMarketCrossGroup newGroup) {
        synchronized (monopolyMarket) {
            monopolyMarket.group = newGroup;
            MonopolyMarketOfficeMgr.resetOffice(monopolyMarket);
            for (MonopolyMarketResGrab resGrab : monopolyMarket.monopolyMarketResGrab.values()) {
                MonopolyMarketResGrabMgr.resetResGrab(monopolyMarket, resGrab, true);
            }
            MonopolyMarketFortressMgr.resetFortress(monopolyMarket);
        }
    }

    /**
     * 关闭分组
     *
     * @param monopolyMarket
     */
    private static void closeMonopolyMarket(MonopolyMarket monopolyMarket) {
        synchronized (monopolyMarket) {
            MonopolyMarketOfficeMgr.closeOffice(monopolyMarket);
            for (MonopolyMarketResGrab resGrab : monopolyMarket.monopolyMarketResGrab.values()) {
                MonopolyMarketResGrabMgr.closeResGrab(monopolyMarket, resGrab);
            }
            // 关闭要塞
            MonopolyMarketFortressMgr.resetFortress(monopolyMarket);
        }
    }


    public static long getGroupId(MonopolyMarket monopolyMarket) {
        return monopolyMarket.group.getGroupId();
    }

    /**
     * 获取玩家数据
     *
     * @return
     */
    public static MonopolyMarketProto.MonopolyMarketCheckUserDataToGameServerMsg.Builder getUserData(long userId, long serverId, UserBaseInfo userBaseInfo, int decorationClass, int decorationOverTime) {
        MonopolyMarketProto.MonopolyMarketCheckUserDataToGameServerMsg.Builder builder = MonopolyMarketProto.MonopolyMarketCheckUserDataToGameServerMsg.newBuilder();
        builder.setUserId(userId);
        MonopolyMarket monopolyMarket = MonopolyMarketMgr.getMonopolyMarket(serverId, true);
        if (monopolyMarket == null) {
            builder.setOfficePosIndex(-1);
            return builder;
        }
        synchronized (monopolyMarket) {
            // 校验榷署位置
            MonopolyMarketOfficeSeatInfo seatInfo = monopolyMarket.monopolyMarketOffice.userSeatMap.get(userId);
            if (seatInfo != null) {
                // 同步位置数据
                CrossUserMgr.updateUserBaseInfo(userId, userBaseInfo);
                seatInfo.baseInfo.setDecorationOverTime(decorationOverTime);
                seatInfo.baseInfo.setDecorationClass((byte) decorationClass);
                synchronized (monopolyMarket.monopolyMarketOffice.updateAndAddSeatInfoSet) {
                    monopolyMarket.monopolyMarketOffice.updateAndAddSeatInfoSet.add(seatInfo);
                }
                int level = MonopolyMarketCommonMgr.calOfficePosLevel(monopolyMarket.monopolyMarketOffice.seatConfigList, seatInfo.baseInfo.getPosIndex());
                builder.setOfficePosIndex(seatInfo.baseInfo.getPosIndex());
                builder.setOfficePosLevel(level);
                builder.setOfficePosNo(MonopolyMarketOfficeMgr.calNo(monopolyMarket, seatInfo.baseInfo.getPosIndex()));
                builder.setOfficeSeatTime(seatInfo.baseInfo.getSeatTime());
            } else {
                MonopolyMarketOfficeFinishData finishData = MonopolyMarketOfficeMgr.userOfficeFinishMap.remove(userId);
                if (finishData != null) {
                    MonopolyMarketProto.MonopolyMarketOfficeRobedRecordEntity.Builder robedRecord = MonopolyMarketProto.MonopolyMarketOfficeRobedRecordEntity.newBuilder();
                    robedRecord.setPosIndex(finishData.getPosIndex());
                    robedRecord.setLevel(finishData.getLevel());
                    robedRecord.setNo(finishData.getNo());
                    robedRecord.setTime(finishData.getTime());
                    robedRecord.setName(finishData.getRobName());
                    finishData.setIsSyn(true);
                    builder.setRobedRecord(robedRecord);
                    synchronized (MonopolyMarketOfficeMgr.tempOfficeFinishList) {
                        MonopolyMarketOfficeMgr.tempOfficeFinishList.add(finishData);
                    }
                    builder.setHasTip(true);
                }
                builder.setOfficePosIndex(-1);
            }
            for (MonopolyMarketResGrab item : monopolyMarket.monopolyMarketResGrab.values()) {
                // 下发正在采集的对象
                Set<MonopolyMarketResGrabPointInfo> pointInfos = item.getUserPointSet(userId, false);
                if (pointInfos != null) {
                    for (MonopolyMarketResGrabPointInfo pointInfo : pointInfos) {
                        if(pointInfo.baseInfo.getUserId() != userId){
                            continue;
                        }
                        MonopolyMarketProto.MonopolyMarketSynDispatchInfoEntity.Builder synDispatchInfo = MonopolyMarketProto.MonopolyMarketSynDispatchInfoEntity.newBuilder();
                        synDispatchInfo.setType(pointInfo.baseInfo.getType());
                        synDispatchInfo.setPosIndex(pointInfo.baseInfo.getPosIndex());
                        synDispatchInfo.setStartTime(pointInfo.baseInfo.getSeatTime());
                        synDispatchInfo.addAllDispatchObjectId(pointInfo.objectInfoMap.keySet());
                        builder.addDispatchInfoList(synDispatchInfo);
                    }
                }
            }
            // 下发玩家要塞派遣信息
            builder.addAllFortressDispatchList(MonopolyMarketFortressMgr.getMonopolyMarketFortressUserDispatchList(monopolyMarket,userId));

            // 是否有资源点结算弹窗
            List<MonopolyMarketResGrabFinishData> resRewardList = MonopolyMarketResGrabMgr.userResGrabFinishMap.get(userId);
            List<MonopolyMarketFortressRewardData> fortressRewardList = MonopolyMarketFortressMgr.userRewardMap.get(userId);
            if ((resRewardList != null && resRewardList.size() > 0 )||
                    (fortressRewardList != null && fortressRewardList.size() > 0) ) {
                builder.setHasTip(true);
            }
        }
        return builder;
    }

    /**
     * 尝试退出 所进入过的位置、据点
     *
     * @param monopolyMarket
     * @param userId
     */
    public static void exitAllSeat(MonopolyMarket monopolyMarket, long userId) {
        // 离开榷署房间
        int officePosIndex = monopolyMarket.monopolyMarketOffice.userInRoomMap.getOrDefault(userId, 0);
        MonopolyMarketOfficeMgr.exitOfficeSeat(monopolyMarket, officePosIndex, userId);
        MonopolyMarketOfficeSeatInfo seatInfo = monopolyMarket.monopolyMarketOffice.seatMap.get(officePosIndex);
        if (seatInfo != null) {
            seatInfo.userMap.remove(userId);
            monopolyMarket.monopolyMarketOffice.userInRoomMap.remove(userId);
        }
        for (MonopolyMarketResGrab resGrab : monopolyMarket.monopolyMarketResGrab.values()) {
            int posIndex = resGrab.userInPointMap.getOrDefault(userId, 0);
            MonopolyMarketResGrabMgr.exitPoint(monopolyMarket, resGrab.type, posIndex, userId);
        }
    }

    /**
     * 检查分组是否发生变化  如果变化 重置 相对应榷场，并通知区服
     */
    public static Set<Long> checkGroupChange(boolean isSyn) {
        logger.info("检查榷场 分组是否发生变化");
        Set<MonopolyMarketCrossGroup> changeGroupSet = MonopolyMarketCrossGroupMgr.checkGroupChange(ConfigHelper.getInt("channelId"));
        // 分组有变化的区服
        Set<Long> changeServerIdSet = new HashSet<>();
        for (MonopolyMarketCrossGroup item : changeGroupSet) {
            MonopolyMarket monopolyMarket = groupMonopolyMarketMap.get(item.getGroupId());
            if (monopolyMarket == null) {
                if (item.getState() == 1) {
                    // 新建的分组
                    monopolyMarket = createMonopolyMarket(item);
                    // 关闭的分组的时候，没有入库。需要重置分组
                    resetMonopolyMarket(monopolyMarket, item);
                }
            } else {
                if (item.getState() == 0) {
                    // 关闭的分组
                    groupMonopolyMarketMap.remove(item.getGroupId());
                    closeMonopolyMarket(monopolyMarket);
                } else {
                    // 改变的分组
                    resetMonopolyMarket(monopolyMarket, item);
                }
            }
            changeServerIdSet.addAll(item.getServerList());
            // 清空聊天
            WorldMessageProto.WorldMessageListMsg.Builder builder = SystemGroupChatMgr.getChatListMsg(eSystemId.MonopolyMarket.getValue(), (int) (item.getGroupId()));
            if (builder != null) {
                builder.clear();
            }
        }
        // 校验边关要塞state是否发生改变
        logger.info("校验边关要塞  state是否发生改变");
        Set<MonopolyMarketCrossGroup> fortressStateChangeGroupSet = MonopolyMarketCrossGroupMgr.checkFortressStateChange(ConfigHelper.getInt("channelId"));
        for (MonopolyMarketCrossGroup item : fortressStateChangeGroupSet){
            MonopolyMarket monopolyMarket = groupMonopolyMarketMap.get(item.getGroupId());
            if (monopolyMarket != null) {
                MonopolyMarketFortressMgr.resetFortress(monopolyMarket);
            }
            changeServerIdSet.addAll(item.getServerList());
        }
        // 跨服启动 下发不了给区服
        if (isSyn) {
            for (long serverId : changeServerIdSet) {
                MonopolyMarketCrossGroupMgr.synMonopolyMarketCrossGroup(serverId);
            }
        }
        return changeServerIdSet;
    }

    /**
     * 加公告
     *
     * @param monopolyMarket
     * @param type
     * @param attackerId
     * @param defenderId
     * @param pos
     */
    public static void addNotice(MonopolyMarket monopolyMarket, int type, long attackerId, long defenderId, int pos) {
        List<MonopolyMarketNoticeData> list = monopolyMarket.noticeMap.get(type);
        if (list == null) {
            list = new ArrayList<>();
            monopolyMarket.noticeMap.put(type, list);
        }
        while (list.size() >= MonopolyMarketMgr.NOTICE_MAX_NUM) {
            list.remove(0);
        }
        MonopolyMarketNoticeData noticeData = new MonopolyMarketNoticeData();
        noticeData.setInsertOption();
        noticeData.setGroupId(monopolyMarket.group.getGroupId());
        noticeData.setType(type);
        noticeData.setUserId(attackerId);
        noticeData.setPos(pos);
        noticeData.setTime(DateHelper.getCurrentSecond());
        noticeData.setRobedId(defenderId);
        list.add(noticeData);
        synchronized (monopolyMarket.needAddNoticeList) {
            monopolyMarket.needAddNoticeList.add(noticeData);
        }
        // 广播
        MonopolyMarketProto.BroadcastMonopolyMarketRespMsg.Builder noticeBroadcast = MonopolyMarketProto.BroadcastMonopolyMarketRespMsg.newBuilder();
        noticeBroadcast.setNewNotice(MonopolyMarketMgr.builderMonopolyMarketNoticeEntity(noticeData));
        for (long serverId : monopolyMarket.group.getServerList()) {
            noticeBroadcast.setType(4);
            MessageHelper.sendPacket(serverId, 0, YanQuMessageUtils.buildMessage(GameProtocol.S_MONOPOLY_MARKET_NOTICE_BROADCAST_FROM_CROSS, noticeBroadcast));
        }
    }

    /**
     * 清空公告
     *
     * @param monopolyMarket
     * @param type
     */
    public static void clearNotice(MonopolyMarket monopolyMarket, int type) {
        List<MonopolyMarketNoticeData> list = monopolyMarket.noticeMap.get(type);
        if (list != null) {
            list.clear();
        }
    }

    public static void initResConfig() {
        crossConfig = MonopolyMarketBussiness.getMonopolyMarketCrossConfig(ConfigHelper.getInt("channelId"));
        if (crossConfig == null) {
            MonopolyMarketBackEndConfig config = MonopolyMarketBussiness.getMonopolyMarketBackEndConfig(ConfigHelper.getInt("channelId"));
            if(!MonopolyMarketCommonMgr.checkBackEndResConfig(config,resConfigList)){
                throw new RuntimeException("榷场资源配置错误。");
            }
            if (config != null) {
                MonopolyMarketConfigMgr.setMonopolyMarketCrossConfig(config);
                crossConfig.setInsertOption();
            } else {
                throw new RuntimeException("后台没有榷场资源配置。");
            }
        }
    }

    /**
     * @param item
     * @return
     */
    public static MonopolyMarketProto.MonopolyMarketNoticeEntity.Builder builderMonopolyMarketNoticeEntity(MonopolyMarketNoticeData item) {
        MonopolyMarketProto.MonopolyMarketNoticeEntity.Builder builder = MonopolyMarketProto.MonopolyMarketNoticeEntity.newBuilder();
        builder.setType(item.getType());
        builder.setRobId(item.getUserId());
        UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(item.getUserId());
        if (userBaseInfo != null) {
            builder.setRobInfo(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
        }
        builder.setPosIndex(item.getPos());
        if (item.getRobedId() > 0) {
            UserBaseInfo robedUserInfo = CrossUserMgr.getUserBaseInfo(item.getRobedId());
            if (robedUserInfo != null) {
                builder.setRobedName(robedUserInfo.getNickName());
            }
        }
        builder.setTime(item.getTime());
        return builder;
    }


    /**
     * 获取最新的公告
     *
     * @return
     */
    public static MonopolyMarketNoticeData getNewMonopolyMarketNoticeData(MonopolyMarket monopolyMarket, int type) {
        MonopolyMarketNoticeData newNotice = null;
        List<MonopolyMarketNoticeData> list = monopolyMarket.noticeMap.get(type);
        if (list.size() > 0) {
            newNotice = list.get(list.size() - 1);
        }
        return newNotice;
    }


    /**
     * 刷新榷场
     *
     * @param monopolyMarket
     * @param now
     */
    public static void refreshMonopolyMarket(MonopolyMarket monopolyMarket, int now) {
        int bit = 0;
        if (MonopolyMarketOfficeMgr.refreshMonopolyMarketOffice(monopolyMarket, now)) {
            bit = BitUtil.set(bit, eMonopolyMarketResType.OFFICE.getValue() - 1, true);
        }
        if (MonopolyMarketResGrabMgr.refreshMonopolyMarketResGrab(monopolyMarket, eMonopolyMarketResType.RES_KING.getValue(), now)) {
            bit = BitUtil.set(bit, eMonopolyMarketResType.RES_KING.getValue() - 1, true);
        }
        if (MonopolyMarketResGrabMgr.refreshMonopolyMarketResGrab(monopolyMarket, eMonopolyMarketResType.RES_QUEEN.getValue(), now)) {
            bit = BitUtil.set(bit, eMonopolyMarketResType.RES_QUEEN.getValue() - 1, true);
        }
        if (MonopolyMarketFortressMgr.refreshMonopolyMarketFortress(monopolyMarket, now)) {
            bit = BitUtil.set(bit, eMonopolyMarketResType.FORTRESS.getValue() - 1, true);
        }
        if (bit > 0) {
            // 系统结束 通知区服玩家重置数据
            MonopolyMarketProto.MonopolyMarketResetToGameServerMsg.Builder synMsg = MonopolyMarketProto.MonopolyMarketResetToGameServerMsg.newBuilder();
            synMsg.setBit(bit);
            for (long serverId : monopolyMarket.group.getServerList()) {
                MessageHelper.sendPacket(serverId, 0, YanQuMessageUtils.buildMessage(GameProtocol.S_MONOPOLY_MARKET_RESET_SYSTEM, synMsg));
            }
            logger.info("榷场系统结束，通知区服玩家重置数据,bit:{}", bit);
        }
    }

    public static void synPatrons(MonopolyMarketResGrab resGrab, long userId, List<MonopolyMarketProto.MonopolyMarketPatronsEntity> list){
        Set<MonopolyMarketResGrabPointInfo> pointInfos =  resGrab.getUserPointSet(userId,false);
        if(pointInfos != null) {
            for (MonopolyMarketProto.MonopolyMarketPatronsEntity item : list) {
                for (MonopolyMarketResGrabPointInfo pointInfo : pointInfos) {
                    IMonopolyMarketObjectInfo objectInfo = pointInfo.objectInfoMap.get(item.getPatronsId());
                    if (objectInfo != null) {
                        MonopolyMarketPatronsInfo patronsInfo = (MonopolyMarketPatronsInfo) objectInfo;
                        patronsInfo.setStageLv(item.getStageLv());
                        patronsInfo.setLevel(item.getLevel());
                        patronsInfo.setSkinId(item.getSkinId());
                        patronsInfo.setEarn(item.getEarn());
                        patronsInfo.setAddPlus(item.getAddPlus());
                        pointInfo.baseInfo.setUpdateOption();
                        resGrab.updateAndAddPointInfoSet.add(pointInfo);
                        break;
                    }
                }
            }
        }
    }

    public static void synBeauty(MonopolyMarketResGrab resGrab, long userId, List<MonopolyMarketProto.MonopolyMarketBeautyEntity> list){
        Set<MonopolyMarketResGrabPointInfo> pointInfos =  resGrab.getUserPointSet(userId,false);
        if(pointInfos != null) {
            for (MonopolyMarketProto.MonopolyMarketBeautyEntity item : list){
                for (MonopolyMarketResGrabPointInfo pointInfo : pointInfos){
                    IMonopolyMarketObjectInfo objectInfo = pointInfo.objectInfoMap.get(item.getId());
                    if(objectInfo != null){
                        MonopolyMarketBeautyInfo patronsInfo = (MonopolyMarketBeautyInfo)objectInfo;

                        patronsInfo.setId(item.getId());
                        patronsInfo.setValue(item.getValue());
                        patronsInfo.setSkinId(item.getSkinId());
                        patronsInfo.setAddPlus(item.getAddPlus());
                        pointInfo.baseInfo.setUpdateOption();
                        resGrab.updateAndAddPointInfoSet.add(pointInfo);
                        break;
                    }
                }
            }
        }
    }

}
